package ch.ethz.ssh2.transport;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.util.Log;

import ch.ethz.ssh2.CldForwardData;
import ch.ethz.ssh2.HTTPProxyException;
import ch.ethz.ssh2.crypto.Base64;
import ch.ethz.ssh2.util.StringEncoder;

public class CldForwardClientTransportManager extends ClientTransportManager {
    private CldForwardData forward;
    private final Socket sock;
	
    public CldForwardClientTransportManager(final Socket socket, final CldForwardData forward) {
        super(socket);
        this.sock = socket;
        this.forward = forward;
    }	

    @Override
    protected void connect(final String hostname, final int port, final int connectTimeout) throws IOException {
		
    	Log.e("SFTP", "[bmt_test] <connect> forwardHost : " + forward.forwardHost);
    	Log.e("SFTP", "[bmt_test] <connect> forwardPort : " + forward.forwardPort);
    	Log.e("SFTP", "[bmt_test] <connect> forwardId : " + forward.forwardId);

		sock.connect(new InetSocketAddress(forward.forwardHost, forward.forwardPort), connectTimeout);

		OutputStream out = sock.getOutputStream();

		/*
		typedef struct clvpn_host_addr{
		    char host[30];
		    unsigned short port ;
		    unsigned long long ID;
		}clvpn_host_addr_t ;
		40 BYTE
		*/
		byte[] buffer = new byte[40];
		int index = 0;
		
		/*ip*/
		byte[] host_buf = hostname.getBytes();
//Log.e("SFTP", "[bmt_test] <establishConnection> hostname len : " + hostname.length());
		System.arraycopy(host_buf, 0, buffer, 0, hostname.length());
		index = 30;

		/*port*/
		buffer[index++] = (byte) (port);
		buffer[index++] = (byte) (port >>> 8);

		/*id*/
		buffer[index++] = (byte) (forward.forwardId);	
		buffer[index++] = (byte) (forward.forwardId >>> 8);
		buffer[index++] = (byte) (forward.forwardId >>> 16);
		buffer[index++] = (byte) (forward.forwardId >>> 24);
		buffer[index++] = (byte) (forward.forwardId >>> 32);
		buffer[index++] = (byte) (forward.forwardId >>> 40);
		buffer[index++] = (byte) (forward.forwardId >>> 48);
		buffer[index++] = (byte) (forward.forwardId >>> 56);

		out.write(buffer);
		out.flush();				
		
		return;
    }
}
